/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticAuto.Base.js
 * @path:   js-src/StatisticOcr/
 * @desc:   StatisticOcr模块下基础业对象类
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
qui(
    function (require, exports, module) {

        StatisticAuto.Grid = function (options) {
            this.dao = StatisticAuto.Dao;
            this.config = StatisticAuto.Config;
            this.options = options || {};
        };

        Com.inherits(StatisticAuto.Grid, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.bindEvent();
                self.initSuggest();
                self.initGrid();
            },
            initGrid: function (options, callback) {
                var self = this;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_AUTO_NEW);
                //params.rowNum=10;
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            initSuggest: function () {
            //    var self = this;
                var fuzzyQuerySuggest = {
                    options: {
                        source: StatisticAuto.urlConfig.redirectUrl,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: StatisticAuto.urlConfig.queryChannelName, type: "get", params: {keyword: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === 200) {
                                data = json.response.list == null ? null : json.response.list;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["channel_name"];
                                itemData[options.labelKey] = item["channel_name"];
                                itemData[self._displayKey] = item["channel_name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["id"];
                        }
                    }
                }

                $("input[name=channelName]").suggest(fuzzyQuerySuggest.options)

                var emailSuggest = {
                    options: {
                        source: StatisticAuto.urlConfig.redirectUrl,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: StatisticAuto.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=user]").suggest(emailSuggest.options);
            },

            bindEvent: function () {
                var self = this;
                self.bindDateTime();
                self.bindBasicEvent();
            },
            bindDateTime: function () {
                var currentDate = new Date();
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() + 86400000);
                var searchEnd = StatisticAuto.Util.formatDateTimeFormat(currentDate);
                currentDate.setTime(currentDate.getTime() - 7 * 86400000);
                var searchStart = StatisticAuto.Util.formatDateTimeFormat(currentDate);
                StatisticAuto.Util.bindDate("startDate", "endDate", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchStart, minDateTime: new Date(searchStart.replace(/-/g, "/"))});
                $("input[name=startDate]").datetimepicker("setDate", new Date(searchStart.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate", new Date(searchEnd.replace(/-/g, "/")));

                StatisticAuto.Util.bindDate("liveBeginTime", "liveEndTime", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchStart, minDateTime: new Date(searchStart.replace(/-/g, "/"))});
                $("input[name=liveBeginTime]").datetimepicker("setDate", new Date(searchStart.replace(/-/g, "/")));
                $("input[name=liveEndTime]").datetimepicker("setDate", new Date(searchEnd.replace(/-/g, "/")));
            },

            bindBasicEvent: function () {
                var self = this;
                $("button[name=reset]").on("click", function (event) {
                    $("input[name=channelName]").suggest("setValue", "");
                    $("input[name=user]").suggest("setValue", "");
                    $("select[tag=form]").val("");
                    self.bindDateTime();
                });
                $('button.query-btn').on('click', function () {
                  //  self.getParam();
                    self.query();
                });
                $("button.query-excel").bind("click", function (event) {
                    StatisticAuto.Util.doDownloadExcel();
                })
                $("button.query-batch").bind("click", function (event) {
                    StatisticAuto.Util.doDownloadBatch();
                })
            },

            query: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },



            getParam: function () {
                var params = {};
                var inputArr =  $('form[name="basicFrm"]').find("input[type=text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("sql")] = element.value.trim()
                    }
                })
                var str = "";
                var selectArr = $('form[name="basicFrm"]').find("select[tag=form]")
                $.each(selectArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        str += element.value + ","
                    }
                })
                var arr = str.split(",");
                var single = null;
                $.each(arr,function(i,element){
                    single = element.split("=");
                    params[single[0]] = single[1];
                })
                console.log("params:="+JSON.stringify(params));
                return { paramsObj :JSON.stringify(params) };
            }

        });
    }
);
